import datetime

import wiringpi
import sys
import time
from paho.mqtt import client as mqtt_client


def receive(real_command, control_a, client_a, topic_a):
    device = '/dev/ttyS3'
    wiringpi.wiringPiSetup()
    serial = wiringpi.serialOpen(device, 115200)
    if serial < 0:
        print("Unable to open serial device: %s" % device)
        sys.exit(-1)
    while True:
        time.sleep(0.1)
        # wiringpi.delayMicroseconds(300000)
        if wiringpi.serialDataAvail(serial) > 0:
            content = wiringpi.serialGetchar(serial)
            if content:
                if len(control_a) == 4 and content == 170:
                    control_a = []
                    print(real_command)
                    if 1 <= real_command <= 20:  # 通过mqtt控制智能家居
                        client_a.publish(topic_a, real_command)
                    if real_command == 21:  # 获取获取当前时间
                        time.sleep(1)
                        get_current_time(serial)
                    if real_command == 22:  # 通过rest获取智能家居温湿度
                        get_rest_data(serial)

                if len(control_a) == 3 and content == 85:
                    control_a.append(content)
                if len(control_a) == 3 and content != 85:
                    control_a = []

                if len(control_a) == 2:
                    real_command = content
                    control_a.append(content)

                if len(control_a) == 1 and content == 85:
                    control_a.append(content)
                if len(control_a) == 1 and content != 85:
                    control_a = []

                if len(control_a) == 0 and content == 170:
                    control_a.append(content)

            # wiringpi.serialFlush(serial)


def get_rest_data(serial):
    url = 'http://192.168.0.108:8123/api/states/sensor.a4c138de770c_temperature'
    headers = {
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI5NWVjNTE2YTE4MmY0NjMxYWUyM2YzZjRiNDY3NjZiZCIsImlhdCI6MTY3NjczMTA4MCwiZXhwIjoxOTkyMDkxMDgwfQ.Es53qdHyxtQblyebe7IB_4AFtV8CqU9Xf5bXGsdpx8w',
        'Content-Type': 'application/json'
    }
    from urllib.request import Request
    from urllib import request
    import json
    try:
        req = Request(url=url, headers=headers)
        response = request.urlopen(req)
        response = response.read().decode('utf-8')
        resDict = json.loads(response)
        if 'state' in resDict:
            arr = resDict['state'].split('.')
            tem1 = int(arr[0])
            tem2 = int(arr[1])
        else:
            tem1 = 20
            tem2 = 4
    except:
        tem1 = 20
        tem2 = 4
    time.sleep(1)
    wiringpi.serialPutchar(serial, 0xAA)
    wiringpi.serialPutchar(serial, 0x55)
    wiringpi.serialPutchar(serial, 0x02)
    wiringpi.serialPutchar(serial, tem1)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, tem2)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x55)
    wiringpi.serialPutchar(serial, 0xAA)  # 通过rest获取智


def get_current_time(serial):
    hour = datetime.datetime.now().hour
    minute = datetime.datetime.now().minute
    wiringpi.serialPutchar(serial, 0xAA)
    wiringpi.serialPutchar(serial, 0x55)
    wiringpi.serialPutchar(serial, 0x01)
    wiringpi.serialPutchar(serial, hour)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, minute)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x00)
    wiringpi.serialPutchar(serial, 0x55)
    wiringpi.serialPutchar(serial, 0xAA)


def on_connect(client_a, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print("Failed to connect, return code %d", rc)


if __name__ == '__main__':
    # 控制数字 从170 85 1 85 170
    command = 0
    control = []
    broker = 'localhost'
    port = 1883
    topic = '/smart-leruge/cmd'
    client = mqtt_client.Client()
    client.on_connect = on_connect
    client.connect(broker, port)
    client.loop_start()
    receive(command, control, client, topic)
